import axios from 'axios';
import { warningAlert } from '@/utils/alert';

const request = axios.create({
  baseURL: 'http://localhost:8081/api/',
  timeout: 5000
});

// 请求拦截器：自动添加token
request.interceptors.request.use(config => {
  // 排除登录/注册接口（不需要携带token）
  const publicUrls = ['/api/auth/login', '/api/auth/register'];
  if (!publicUrls.includes(config.url)) {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器：处理token过期
request.interceptors.response.use(response => {
  return response.data;
}, error => {
  if (error.response) {
    if (error.response.status === 401) {
      // token无效或过期，清除本地存储并跳转登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
      warningAlert('登录已过期，请重新登录', '提示');
    }
  }
  
  return Promise.reject(error);
});

export default request;